const path = require('path')
const Client = require('ssh2-sftp-client')

const client = new Client()
const { NodeSSH } = require('node-ssh');

const argv = process.argv
const env = argv[argv.length - 1]
const config = require('../deployment.server.json')
const jsonCompiler = require('./compiler')
const envConfig = jsonCompiler(config[env])
const srcDir = path.join(__dirname, '../dist')
const targetDir = envConfig.targetDir
const { host, port, username, password } = envConfig
const authConfig = {
  host,
  port,
  username,
  password
}
const ssh = new NodeSSH();
const mvDir = () => {
  ssh.connect(authConfig).then(() => {
    // console.log('SSH login success');
    ssh.execCommand('cmd /c move ' + envConfig.mvFrom + ' ' + envConfig.mvTo).then(result => {
      // console.log(`The exec message is: ${result.stdout}`, result);
      // console.log('process', process)
      if (!result.stderr) {
        console.log('部署成功!');
        process.exit(0);
      } else {
        console.log('移动过程发生错误:', result);
        process.exit(0);
      }
    });
  }).catch((err) => {
    console.log('连接服务器失败:', err);
    process.exit(0);
  });
}
client.connect(authConfig).then(() => {
  console.log('连接成功 开始上传...')
  return client.uploadDir(srcDir, targetDir, /^((?!apiConfig\.js).)+$/).then(res => {
    console.log('上传成功, 开始移动位置...')
    mvDir()
  })
}).catch((err) => {
  console.log('连接服务器失败', err);
});